'use strict';
var socket=$.WebSocketMgr();
var eventMgr=$.EventMgr();
var dataEncrypt=$.DataEncrypt();
socket.initConnection(eventMgr.assignedEvent);
//生成一个api的序列号 保证请求的顺序
function getSeqNum() {
	actionSeqNum ++;
	return actionSeqNum;
}


function registerEvent() {
	eventMgr.addEvent(LoginCmdID.CID_LOGIN_RES_USERLOGIN,handleResForLogin);//登录请求后,服务的应答
	eventMgr.addEvent(MessageCmdID.CID_MSG_DATA,handleResForNewMsg);//服务端向客户端发的消息
	eventMgr.addEvent(MessageCmdID.CID_MSG_DATA_ACK,handleResForMsgAck);//客户端发消息成功后,服务端的应答
	eventMgr.addEvent(MessageCmdID.CID_MSG_LIST_RESPONSE,handleResForMsgList);//客户端请求消息列表得到的应答
	eventMgr.addEvent(MessageCmdID.CID_MSG_UNREAD_CNT_RESPONSE,handleUnReadMessageCnt);//客户端请求未读消息得到的应答
	eventMgr.addEvent(GroupCmdID.CID_GROUP_NORMAL_LIST_RESPONSE,handleGroupNormalList);//客户端请求群列表得到应答
	eventMgr.addEvent(GroupCmdID.CID_GROUP_INFO_RESPONSE,handleGroupInfoRes);//客户端请求群详情得到的应答
	eventMgr.addEvent(BuddyListCmdID.CID_BUDDY_LIST_RECENT_CONTACT_SESSION_RESPONSE,handleResForRecentlySession);//请求最近会话列表服务端的应答
	eventMgr.addEvent(BuddyListCmdID.CID_BUDDY_LIST_ALL_USER_RESPONSE,handleResForAllFriends);
	eventMgr.addEvent(BuddyListCmdID.CID_BUDDY_LIST_USER_INFO_RESPONSE,handleResForFriendsByIds);
	eventMgr.addEvent(OtherCmdID.CID_OTHER_HEARTBEAT,answerHeartBeat);
}
registerEvent();

app.controller('TodoCtrl', function($scope) {
	$scope.usn="heroloss";
	$scope.pwd="123456";
  	$scope.onLogin = function() {
		//alert($scope.usn);
		var loginData = {username:$scope.usn,password:md5($scope.pwd)};
		//alert($scope.pwd);
		console.log(loginData);
		loginAction(loginData,function(state,resData){
		if(state) {
			imDb.initDb();
			getAllFriends({},function(state,res){
				//console.log(res);
				var users = res.user_list;
				for(var id in users) {
					var user = users[id];
					imDb.addUsertoDb(user.user_id,user);
				}
			});
			
		}else {
			myApp.hideIndicator();
			alert(resData);
		}
	});
  	};
});


function loginAction(info,callback) {
	var LoginReq = IMLogin.build('IM.Login.IMLoginReq');
	info.client_version = '1.0';
	info.client_type = 1;
	info.online_status = UserStatType.USER_STATUS_ONLINE;
	socket.wsConnection.loginInfo = info;
	var loginReq = new LoginReq();
	loginReq.set("user_name",'' + info.username);
	loginReq.set("password", info.password);
	loginReq.set("online_status",UserStatType.USER_STATUS_ONLINE);
	loginReq.set("client_type",1);
	loginReq.set("client_version","1.0");
  
    var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
    var buffer = buildPackage(loginReq.toArrayBuffer(),ServiceID.SID_LOGIN,LoginCmdID.CID_LOGIN_REQ_USERLOGIN,sn);
	socket.sendBinaryData(buffer.buffer);
}

function buildPackage(req,serviceId,commandId,seqNum)
{
	var length = req.byteLength;
	var ByteBuffer =  dcodeIO.ByteBuffer;
	var bb = new ByteBuffer();
	bb.writeUInt32(length + 16);
	bb.writeUInt16(0);
	bb.writeUInt16(0);
	bb.writeUInt16(serviceId);
	bb.writeUInt16(commandId);
	bb.writeUInt16(seqNum);
	bb.writeUInt16(0);
	bb.append(req);
	return bb;
}

function relogin(callback){
	console.log("do relogin");
	if(!!socket.wsConnection.loginInfo) {
		loginAction(socket.wsConnection.loginInfo,callback);
	}
}

//发消息的api
function sendMsgApiAction(msg,callback) {
	
	//var content = {from_user_id:socket.wsConnection.uid,to_session_id:group_id,msg_data:text,msg_type:MsgType.MSG_TYPE_GROUP_TEXT,msg_id:local_msg_id,created:Date.parse(new Date())/ 1000};
	var IMMsgData = IMMessage.build('IM.Message.IMMsgData');
	var msgData = new IMMsgData();
	var msgContent = aesEncryptText(msg.msg_data);
	msgData.set('from_user_id',msg.from_user_id);
	msgData.set('to_session_id',msg.to_session_id);
	msgData.set('msg_data', Base64.encode(msgContent));
	msgData.set('msg_type',msg.msg_type);
	msgData.set('msg_id',msg.msg_id);
	msgData.set('create_time',msg.created);

	var api = {msg:msg , callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,api);
    var buffer = buildPackage(msgData.toArrayBuffer(),ServiceID.SID_MSG,MessageCmdID.CID_MSG_DATA,sn);
	socket.sendBinaryData(buffer.buffer);
}


//消息发送到服务器成功
function handleResForMsgAck(data) {

	var IMMsgDataAck = IMMessage.build('IM.Message.IMMsgDataAck');
	var msg = IMMsgDataAck.decode(data.content.slice(16));
		var sendMsgApi = apiHashMap.Get(data.seqNum);
		if(!!sendMsgApi) {
			sendMsgApi.msg.msg_id =  msg.msg_id;
			sendMsgApi.callback(true,sendMsgApi.msg);
			apiHashMap.Remove(data.content.seqNum);
		}
}


//获取群列表
function getGroupListApiAction(callback) {
	var IMNormalGroupListReq = IMGroup.build('IM.Group.IMNormalGroupListReq');
	var groupListReq  = new IMNormalGroupListReq();
	groupListReq.set("user_id",socket.wsConnection.uid);
	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(groupListReq.toArrayBuffer(),ServiceID.SID_GROUP,GroupCmdID.CID_GROUP_NORMAL_LIST_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}

//处理服务端返回的群列表
function handleGroupNormalList(data) {
	var IMNormalGroupListRsp = IMGroup.build('IM.Group.IMNormalGroupListRsp');
	var msg = IMNormalGroupListRsp.decode(data.content.slice(16));
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp);
}


//获取群详情
function getGroupInfoApiAction(content,callback) {
	console.log(content);
	var IMGroupInfoListReq = IMGroup.build('IM.Group.IMGroupInfoListReq');
	var infolistReq = new IMGroupInfoListReq();
	infolistReq.set("user_id", socket.wsConnection.uid);
	infolistReq.set("group_version_list", content.group_version_list);
	//console.log(infolistReq);
	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(infolistReq.toArrayBuffer(),ServiceID.SID_GROUP,GroupCmdID.CID_GROUP_INFO_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}

//处理服务端返回的群详情
function handleGroupInfoRes(data) {
	var IMGroupInfoListRsp = IMGroup.build('IM.Group.IMGroupInfoListRsp');
	var msg = IMGroupInfoListRsp.decode(data.content.slice(16));
	console.log(msg);
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp);   
}

//获信息列表
function getMsgListApiAction(content,callback) {
	var IMGetMsgListReq = IMMessage.build('IM.Message.IMGetMsgListReq');
	var imgetmegListReq = new IMGetMsgListReq();
	imgetmegListReq.set('user_id', socket.wsConnection.uid);
	imgetmegListReq.set('session_type', content.session_type);
	imgetmegListReq.set('session_id', content.session_id);
	imgetmegListReq.set('msg_id_begin', content.msg_id_begin);
	imgetmegListReq.set('msg_cnt', content.msg_cnt);

	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(imgetmegListReq.toArrayBuffer(),ServiceID.SID_MSG,MessageCmdID.CID_MSG_LIST_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}

//处理服务端应答回来的消息列表
function handleResForMsgList(data) {
	var IMGetMsgListRsp = IMMessage.build('IM.Message.IMGetMsgListRsp');
	var msg = IMGetMsgListRsp.decode(data.content.slice(16));
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp);   
}

//获取最近会话列表
function getRecentlySession(content,callback){
	var IMRecentContactSessionReq = IMBuddy.build('IM.Buddy.IMRecentContactSessionReq');
	var recentSessionReq = new IMRecentContactSessionReq();
	recentSessionReq.set("user_id",socket.wsConnection.uid);
	recentSessionReq.set('latest_update_time',content.latest_update_time);
	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(recentSessionReq.toArrayBuffer() ,ServiceID.SID_BUDDY_LIST ,BuddyListCmdID.CID_BUDDY_LIST_RECENT_CONTACT_SESSION_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}


function handleResForRecentlySession(data)
{
	var IMRecentContactSessionRsp = IMBuddy.build('IM.Buddy.IMRecentContactSessionRsp');
	var msg = IMRecentContactSessionRsp.decode(data.content.slice(16));
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp);  
}



//获取所有好友列表(单聊的时候会用上)
function getAllFriends(content,callback){
	//content.user_id = socket.wsConnection.uid;
	var IMAllUserReq = IMBuddy.build('IM.Buddy.IMAllUserReq');
	var imAllUserReq = new IMAllUserReq();
	imAllUserReq.set('user_id',socket.wsConnection.uid);
	imAllUserReq.set('latest_update_time',0);

	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(imAllUserReq.toArrayBuffer() ,ServiceID.SID_BUDDY_LIST ,BuddyListCmdID.CID_BUDDY_LIST_ALL_USER_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}


function handleResForAllFriends(data) {
	var IMAllUserRsp = IMBuddy.build('IM.Buddy.IMAllUserRsp');
	var msg = IMAllUserRsp.decode(data.content.slice(16));
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp); 
}


function getFriendsByIds(ids,callback) {
	if(!ids || ids.length == 0) {
		return;
	}
	var IMUsersInfoReq = IMBuddy.build('IM.Buddy.IMUsersInfoReq');
	var imUsersInfoReq = new IMUsersInfoReq();
	imUsersInfoReq.set('user_id',socket.wsConnection.uid);
	imUsersInfoReq.set('user_id_list',ids);
	//console.log(imUsersInfoReq);

	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(imUsersInfoReq.toArrayBuffer() ,ServiceID.SID_BUDDY_LIST ,BuddyListCmdID.CID_BUDDY_LIST_USER_INFO_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}


function handleResForFriendsByIds(data){
	var IMUsersInfoRsp = IMBuddy.build('IM.Buddy.IMUsersInfoRsp');
	var msg = IMUsersInfoRsp.decode(data.content.slice(16));
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp); 
}

//获取未读消息
function getUnreadMessageCnt(content,callback){
	var IMUnreadMsgCntReq = IMMessage.build('IM.Message.IMUnreadMsgCntReq');
	var imUnreadMsgCntReq = new IMUnreadMsgCntReq();
	imUnreadMsgCntReq.set('user_id',socket.wsConnection.uid);
	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(imUnreadMsgCntReq.toArrayBuffer() ,ServiceID.SID_MSG ,MessageCmdID.CID_MSG_UNREAD_CNT_REQUEST,sn);
	socket.sendBinaryData(buffer.buffer);
}

function handleUnReadMessageCnt(data) {
	var IMUnreadMsgCntRsp = IMMessage.build('IM.Message.IMUnreadMsgCntRsp');
	var msg = IMUnreadMsgCntRsp.decode(data.content.slice(16));
	var rsp = {};
	rsp.seqNum = data.seqNum;
	rsp.content = msg;
	simpleWorkForHandle(rsp);
}


//应答给服务端 读了这条消息
function answerMsg(content,callback){
	var IMMsgDataReadAck = IMMessage.build('IM.Message.IMMsgDataReadAck');
	var msgDataReadAck = new IMMsgDataReadAck();
	msgDataReadAck.set('user_id', socket.wsConnection.uid);
	msgDataReadAck.set('session_id', content.session_id);
	msgDataReadAck.set('msg_id', content.msg_id);
	msgDataReadAck.set('session_type', content.session_type);

	var sendMsgApi = {callback:callback};
	var sn = getSeqNum();
	apiHashMap.Set(sn,sendMsgApi);
	var buffer = buildPackage(msgDataReadAck.toArrayBuffer() ,ServiceID.SID_MSG ,MessageCmdID.CID_MSG_READ_ACK,sn);
	socket.sendBinaryData(buffer.buffer);
}

//应答来自服务端的心跳包
function answerHeartBeat()
{
	var IMHeartBeat = IMGroup.build('IM.Other.IMHeartBeat');
	var hearBeat = new IMHeartBeat();
	var buffer = buildPackage(hearBeat.toArrayBuffer(),ServiceID.SID_OTHER,OtherCmdID.CID_OTHER_HEARTBEAT,sn);
	socket.sendBinaryData(buffer.buffer);
}



function handleResForLogin(data) {
    var IMLoginRes = IMLogin.build('IM.Login.IMLoginRes');
    console.log(data);
	var msg = IMLoginRes.decode(data.content.slice(16));
	console.log(msg);
	if(msg) {
		var loginApi = apiHashMap.Get(data.seqNum);
		if(msg.result_code == ResultType.REFUSE_REASON_NONE) {
			socket.wsConnection.logined = true;
			socket.wsConnection.uid = msg.user_info.user_id;
			socket.wsConnection.user = msg.user_info;
			loginApi.callback(true,msg.user_info);
		}else {
			loginApi.callback(false,msg.result_string);
		}
	}
}

//收到一条新消息
function handleResForNewMsg(data) {
	if(data.content) {
		if(typeof socket.wsConnection.msgHandler === "function") {
			var IMMsgData = IMMessage.build('IM.Message.IMMsgData');
			var msg = IMMsgData.decode(data.content.slice(16));
			socket.wsConnection.msgHandler(msg);
		}
	}
}

//简单的处理了api的应答结果
function simpleWorkForHandle(data) {
	if(data.content) {
		console.log("finish api for seqNum:" + data.seqNum);
		var api = apiHashMap.Get(data.seqNum);
		if(!!api) {
			api.callback(true,data.content);
			apiHashMap.Remove(data.seqNum);    
		}
	}
}

//给指定群号发送一条消息
function sendGroupTextMsg(text,group_id,callback) {
	var content = {from_user_id:socket.wsConnection.uid,to_session_id:group_id,msg_data:text,msg_type:MsgType.MSG_TYPE_GROUP_TEXT,msg_id:local_msg_id,created:Date.parse(new Date())/ 1000};
	local_msg_id++;
	sendMsgApiAction(content,callback);
}

//给指定用户发送一条消息
function sendSingleTextMsg(text,to_user_id,callback) {
	var content = {from_user_id:socket.wsConnection.uid,to_session_id:to_user_id,msg_data:text,msg_type:MsgType.MSG_TYPE_SINGLE_TEXT,msg_id:local_msg_id,created:Date.parse(new Date())/ 1000};
	local_msg_id++;
	sendMsgApiAction(content,callback);
}